﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System.Threading;
using System.Windows.Forms;
using System.Data.SQLite;

namespace seo_tool.lib
{
    class Xiangguan
    {
        struct Item
        {
            public string keyword;
            public int pid;
            public int level;
            public string xiala;
            public string xiangguan;
            public string is_run;
            public string search;
        };

        IWebDriver driver;
        string search;
        Sqlite conn;
        DataGridView dataGridViewData;
        RichTextBox richTextBoxInfo;



        public Xiangguan(string search, Sqlite conn, DataGridView dataGridViewData, RichTextBox richTextBoxInfo)
        {
            this.search = search;
            this.conn = conn;
            this.dataGridViewData = dataGridViewData;
            this.richTextBoxInfo = richTextBoxInfo;
        }

        public void Start()
        {
            var chromeDriverService = ChromeDriverService.CreateDefaultService();
            chromeDriverService.HideCommandPromptWindow = true;

            ChromeOptions options = new ChromeOptions();
            //var proxy = new Proxy();
            //proxy.Kind = ProxyKind.Manual;
            //proxy.IsAutoDetect = false;
            //proxy.HttpProxy = "localhost:8080";
            //proxy.SslProxy = "localhost:8080";
            //options.Proxy = proxy;
            options.AddArgument(string.Format("--user-agent={0}", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36"));
            options.AddArguments("--ignore-certificate-errors");
            options.AddArguments("--ignore-ssl-errors");
            options.AddArgument("--headless");
            options.AddArgument("--disable-gpu");
            options.AddArgument("--hide-scrollbars");
            options.AddArgument("--incognito");
            options.AddArgument("--disable-web-security");
            options.AddArgument("--no-sandbox");
            options.AddArgument("lang=zh_CN.UTF-8");
            options.AddExcludedArgument("enable-automation");
            options.AddAdditionalCapability("useAutomationExtension", false);
            options.AddUserProfilePreference("profile.default_content_setting_values.images", 2);//禁用图片
            options.AddArgument("disable-blink-features=AutomationControlled");

            string url = null;
            switch (search)
            {
                case "百度PC":
                    url = "https://www.baidu.com/";
                    break;
                case "搜狗PC":
                    url = "https://www.sogou.com/";
                    break;
                case "百度M":
                    url = "https://m.baidu.com/";
                    break;
                case "搜狗M":
                    url = "https://m.sogou.com/";
                    break;
                case "神马M":
                    url = "https://m.sm.cn/";
                    break;
            }
            if (search == "百度M" || search == "搜狗M" || search == "神马M")
            {
                ChromeMobileEmulationDeviceSettings CMEDS = new ChromeMobileEmulationDeviceSettings();
                CMEDS.Width = 436; //设置窗体显示宽高
                CMEDS.Height = 687;
                CMEDS.PixelRatio = 1.0;
                CMEDS.UserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25";
                options.EnableMobileEmulation(CMEDS);
            }
            driver = new ChromeDriver(chromeDriverService, options);
            driver.Navigate().GoToUrl(url);
        }

        public void Run(int level)
        {
            Start();
            EchoInfo("chromedriver已开启！");
            RunStart();

            for (int i = 1; i <= level; i++)
            {
                int index = dataGridViewData.Rows.Count - 1;
                GetMore(i);
                RunStart(index);
            }
            
            Close();
            EchoInfo("chromedriver已关闭！");
        }

        private void RunStart(int index = 0)
        {
            Item item;
            for (int i = index; i < dataGridViewData.Rows.Count - 1; i++)
            {
                string keyword = dataGridViewData.Rows[i].Cells["keyword"].Value.ToString();
                string id = dataGridViewData.Rows[i].Cells["id"].Value.ToString();
                EchoInfo("开始执行：" + keyword);

                if (search == "百度PC")
                {
                    item = Baidu(keyword);
                }
                else if (search == "搜狗PC")
                {
                    item = Sougou(keyword);
                }
                else if (search == "百度M")
                {
                    item = BaiduM(keyword);
                }
                else if (search == "搜狗M")
                {
                    item = SougouM(keyword);
                }
                else if (search == "神马M")
                {
                    item = ShenmaM(keyword);
                }
                else
                {
                    Close();
                    EchoInfo("search错误");
                    return;
                }

                conn.update($"update xiangguan set xiala = '{item.xiala}', xiangguan = '{item.xiangguan}', is_run = '{item.is_run}', search = '{item.search}' where id = '{id}'");
                dataGridViewData.Rows[i].Cells["xiala"].Value = item.xiala;
                dataGridViewData.Rows[i].Cells["xiangguan"].Value = item.xiangguan;
                dataGridViewData.Rows[i].Cells["is_run_xg"].Value = item.is_run;
                dataGridViewData.Rows[i].Cells["search_xg"].Value = item.search;
                EchoInfo("ok");
            }
        }

        private void GetMore(int level)
        {
            SQLiteDataReader reader = conn.getXiangguan(level-1);
            while (reader.Read())
            {
                string[] kws = reader["xiala"].ToString().Split('|');
                foreach (string kw in kws)
                {
                    int insertId = conn.insertGetId($"insert into xiangguan (keyword, pid, level) values ('{kw}', {reader["id"]}, {level});select last_insert_rowid();");
                    int index = dataGridViewData.Rows.Add();
                    dataGridViewData.Rows[index].Cells["id"].Value = insertId;
                    dataGridViewData.Rows[index].Cells["keyword"].Value = kw;
                    dataGridViewData.Rows[index].Cells["pid"].Value = reader["id"];
                    dataGridViewData.Rows[index].Cells["level"].Value = level;
                }
                Thread.Sleep(500);
            }
            reader.Close();
        }

        private Item Baidu(string keyword)
        {
            Item item = new Item();
            item.keyword = keyword;
            item.pid = 0;
            item.level = 0;
            item.xiala = "";
            item.xiangguan = "";
            item.is_run = "已执行";
            item.search = "百度PC";

            driver.FindElement(By.XPath(".//input[@id='kw']")).Clear();
            driver.FindElement(By.XPath(".//input[@id='kw']")).SendKeys(keyword);
            driver.FindElement(By.XPath(".//input[@id='su']")).Click();
            Thread.Sleep(2000);
            var table = driver.FindElements(By.XPath("//*[text()='相关搜索']/../table//a"));
            foreach (var a in table)
            {
                item.xiangguan += a.Text + "|";
            }
            item.xiangguan = item.xiangguan.TrimEnd('|');

            driver.FindElement(By.XPath(".//input[@id='kw']")).Click();
            Thread.Sleep(2000);
            var ul = driver.FindElements(By.XPath("//div[@class='bdsug bdsug-new bdsugbg']/ul/li"));
            foreach (var li in ul)
            {
                item.xiala += li.Text + "|";
            }
            item.xiala = item.xiala.TrimEnd('|');

            return item;
        }

        private Item Sougou(string keyword)
        {
            Item item = new Item();
            item.keyword = keyword;
            item.pid = 0;
            item.level = 0;
            item.xiala = "";
            item.xiangguan = "";
            item.is_run = "已执行";
            item.search = "搜狗PC";

            try
            {
                driver.FindElement(By.XPath(".//input[@id='upquery']")).SendKeys(OpenQA.Selenium.Keys.LeftControl + "a");
                Thread.Sleep(500);
                driver.FindElement(By.XPath(".//input[@id='upquery']")).SendKeys(OpenQA.Selenium.Keys.Delete);
                Thread.Sleep(500);
                driver.FindElement(By.XPath(".//input[@id='upquery']")).SendKeys(keyword);
                driver.FindElement(By.XPath(".//input[@id='searchBtn']")).Click();
            }
            catch
            {
                driver.FindElement(By.XPath(".//input[@id='query']")).Clear();
                driver.FindElement(By.XPath(".//input[@id='query']")).SendKeys(keyword);
                driver.FindElement(By.XPath(".//input[@id='stb']")).Click();
            }
            Thread.Sleep(2000);
            var table = driver.FindElements(By.XPath("//table[@id='hint_container']//a"));
            foreach (var a in table)
            {
                item.xiangguan += a.Text + "|";
            }
            item.xiangguan = item.xiangguan.TrimEnd('|');

            driver.FindElement(By.XPath(".//input[@id='upquery']")).Click();
            Thread.Sleep(2000);
            var ul = driver.FindElements(By.XPath(".//ul[@class='suglist']/li"));
            foreach (var li in ul)
            {
                item.xiala += li.Text + "|";
            }
            item.xiala = item.xiala.TrimEnd('|');

            return item;
        }

        private Item BaiduM(string keyword)
        {
            Item item = new Item();
            item.keyword = keyword;
            item.pid = 0;
            item.level = 0;
            item.xiala = "";
            item.xiangguan = "";
            item.is_run = "已执行";
            item.search = "百度M";
            return item;
        }

        private Item SougouM(string keyword)
        {
            Item item = new Item();
            item.keyword = keyword;
            item.pid = 0;
            item.level = 0;
            item.xiala = "";
            item.xiangguan = "";
            item.is_run = "已执行";
            item.search = "搜狗M";
            return item;
        }

        private Item ShenmaM(string keyword)
        {
            Item item = new Item();
            item.keyword = keyword;
            item.pid = 0;
            item.level = 0;
            item.xiala = "";
            item.xiangguan = "";
            item.is_run = "已执行";
            item.search = "神马M";
            return item;
        }

        public void Close()
        {
            driver.Close();
            driver.Quit();
            driver.Dispose();
        }

        private void EchoInfo(string info)
        {
            richTextBoxInfo.Text += info + "\r\n";
            richTextBoxInfo.SelectionStart = richTextBoxInfo.Text.Length;
            richTextBoxInfo.ScrollToCaret();
            richTextBoxInfo.Refresh();
        }

        ~Xiangguan()
        {
            driver.Close();
            driver.Quit();
            driver.Dispose();
        }


    }
}
